package com.ruoyi.framework.config;

import java.text.SimpleDateFormat;
import java.util.TimeZone;
import java.util.Date;
import java.text.ParseException;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;

/**
 * 程序注解配置
 *
 * @author ruoyi
 */
@Configuration
// 表示通过aop框架暴露该代理对象,AopContext能够访问
@EnableAspectJAutoProxy(exposeProxy = true)
// 指定要扫描的Mapper类的包的路径
@MapperScan("com.ruoyi.**.mapper")
public class ApplicationConfig
{
    /**
     * 统一日期反序列化器
     */
    public static class UnifiedDateDeserializer extends JsonDeserializer<Date> {
        private static final String[] FORMATS = {
            "yyyy-MM-dd HH:mm:ss",
            "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",
            "yyyy-MM-dd'T'HH:mm:ss'Z'",
            "yyyy-MM-dd"
        };
        private static final String[] TIMEZONES = {"GMT+8", "UTC", "UTC", "GMT+8"};

        @Override
        public Date deserialize(JsonParser p, DeserializationContext ctxt) throws java.io.IOException {
            String date = p.getText();
            if (date == null || date.trim().isEmpty()) {
                return null;
            }

            for (int i = 0; i < FORMATS.length; i++) {
                try {
                    SimpleDateFormat sdf = new SimpleDateFormat(FORMATS[i]);
                    sdf.setTimeZone(TimeZone.getTimeZone(TIMEZONES[i]));
                    return sdf.parse(date);
                } catch (ParseException ignored) {
                    // 继续尝试下一个格式
                }
            }
            throw new java.io.IOException("无法解析日期格式: " + date);
        }
    }

    /**
     * Jackson配置
     */
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jacksonObjectMapperCustomization()
    {
        return builder -> {
            builder.timeZone(TimeZone.getDefault())
                   .dateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))
                   .featuresToDisable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
                   .deserializerByType(Date.class, new UnifiedDateDeserializer());
        };
    }
}
